package com.ruoyi.common.core.domain;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("isNotAutoSetField")) {
            Boolean isNotAutoSetField = (Boolean) metaObject.getValue("isNotAutoSetField");
            if (isNotAutoSetField != null && isNotAutoSetField) {
                return;
            }
        }

        //setFieldValByName:参数1：字段名，参数2：赋值，参数3：metaObject
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (metaObject.hasSetter("delFlag")) {
            this.setFieldValByName("delFlag", Constants.NOT_DELETE, metaObject);
        }
        try {
            String username = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(username)) {
                this.setFieldValByName("createBy", username, metaObject);
                this.setFieldValByName("updateBy", username, metaObject);
            }
        } catch (Exception ignored) {

        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("isNotAutoSetField")) {
            Boolean isNotAutoSetField = (Boolean) metaObject.getValue("isNotAutoSetField");
            if (isNotAutoSetField != null && isNotAutoSetField) {
                return;
            }
        }

        this.setFieldValByName("updateTime", new Date(), metaObject);
        try {
            String username = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(username)) {
                this.setFieldValByName("updateBy", username, metaObject);
            }
        } catch (Exception ignored) {

        }
    }
}
